/**
 * JWT验证
 */
const jwt = require('jsonwebtoken');

/**
 * 验证token是否存在及过期
 */
module.exports = (req, res, next) => {
    try {
        // token是从Request的Headers中获得的
        // token值类似[Bearer 'token值']
        // Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImNoaWFuZ2J0MkBnZW9wb3J0YWwuY24iLCJ1c2VySWQiOiI1YzkwYWQ5NjliOWE1MTIyZTIzMzJmNDYiLCJpYXQiOjE1NTI5ODcxMjUsImV4cCI6MTU1MzA3MzUyNX0.rKx0KgqitlV2-e0mjxoC6VPcGYsTc-I0R96_UBGJPYU
        const token = req.headers.authorization.split(" ")[1];
        const decoded = jwt.verify(token, process.env.SecretOrPublicKey);

        req.userData = decoded;
        next();
    } catch (error) {
        return res.status(401).json({
            message: 'Auth验证失败,请重新获取token'
        });
    }
};